package bold.deposit.useful;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.ServletRequestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RequestUtil extends ServletRequestUtils {
    public static Map<String, String> getMap(HttpServletRequest request) {
        Map<String, String[]> map = request.getParameterMap();
        Map<String, String> params = new HashMap<>(map.size());

        for (Map.Entry<String, String[]> entry : map.entrySet()) {
            String key = entry.getKey();
            String[] value = entry.getValue();

            if (value.length > 1) {
                List<String> arr = new ArrayList<>();
                for (int i = 0; i < value.length; i++) {
                    if (StringUtils.isNotBlank(value[i])) {
                        arr.add(value[i]);
                    }
                }
                if (!arr.isEmpty()) {
                    params.put(key, String.join(",", arr));
                }
            } else {
                if (StringUtils.isNotBlank(value[0])) {
                    params.put(key, value[0]);
                }
            }

        }
        return params;
    }

    public static Map<String, String> getAllMap(HttpServletRequest request) {
        Map<String, String[]> map = request.getParameterMap();
        Map<String, String> params = new HashMap<>(map.size());

        for (Map.Entry<String, String[]> entry : map.entrySet()) {
            String key = entry.getKey();
            String[] value = entry.getValue();

            if (value.length > 1) {
                List<String> arr = new ArrayList<>();
                for (int i = 0; i < value.length; i++) {
                    if (StringUtils.isNotBlank(value[i])) {
                        arr.add(value[i]);
                    }
                }
                if (arr.isEmpty()) {
                    params.put(key, null);
                } else {
                    params.put(key, String.join(",", arr));
                }
            } else {
                if (StringUtils.isNotBlank(value[0])) {
                    params.put(key, value[0]);
                } else {
                    params.put(key, null);
                }
            }

        }
        return params;
    }

}
